const errorTypes = require('../constants/error-types')
const userService = require('../service/user.service')
const md5password = require('../utils/password-handle');
//登录
const verifyLogin = async (ctx, next) => {
  console.log('开始验证用户身份');
  const { name, password } = ctx.request.body;
  console.log(name,'9999');
  if (!name || !password) {
    const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
    console.log('账号密码为空');
    return ctx.app.emit('error', error, ctx);
  }
  const res = await userService.getUserByName(name)
  const user = res[0][0];
  console.log(user);
  if (!user) {
    const error = new Error(errorTypes.USER_DOES_NOT_EXISTS);
    return ctx.app.emit('error', error, ctx);
  }
    // if (md5password(password)!== user.password) {
    //   console.log('1');  
    //   const error = new Error(errorTypes.PASSWORD_IS_INCORRENT);
    //   return ctx.app.emit('error', error, ctx);
    // }
  ctx.user = user;
  await next();
}
//注册
const verifyCreate = async (ctx, next) => {
  console.log('来到了注册接口');
  const { name, password } = ctx.request.body
  console.log(name, password,'name, password');
  const res = await userService.getUserByName(name)
  const user = res[0];
  if (user.length<1) {
    await userService.create(name, md5password(password))
    ctx.user = user;
    await next()
  } else {
    const error = new Error(errorTypes.USERISEXIST)
    return ctx.app.emit('error',error,ctx)
  }
}
//验证是否登陆
const verifyAuth = async (ctx, next) => {
  console.log("验证授权的middleware~");
  // 1.获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    const error = new Error(errorTypes.UNAUTHORIZATION);
    return ctx.app.emit('error', error, ctx);
  }
  const token = authorization.replace('Bearer ', '');

  // 2.验证token(id/name/iat/exp)
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"]
    });
    ctx.user = result;
    await next();
  } catch (err) {
    const error = new Error(errorTypes.UNAUTHORIZATION);
    ctx.app.emit('error', error, ctx);
  }
}
//获取用户当前及时的私信 
const getwspvmsg = async(ctx,next)=>{
  console.log('来到了这');
  const userid = ctx.url.split('/')
    ctx.pvwsmsg = await userService.getwspvmsg(userid[userid.length-1])
    await next()
}
//获取当前用户私信
const getpvmsg = async(ctx,next)=>{
  console.log('来到了这');
  const userid = ctx.url.split('/')
 const data = await userService.getpvmsg(userid[userid.length-1])
  ctx.pvmsg = data[0]
    await next()
}
module.exports = {
  verifyLogin,
  verifyCreate,
  verifyAuth,
  getwspvmsg,
  getpvmsg
}